package com.sitech.webapp.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sitech.BaseConst;
import com.sitech.context.SpringContext;
import com.sitech.domain.Auth;
import com.sitech.domain.LoginUser;
import com.sitech.service.AuthService;

public class AuthInitFilter implements Filter
{
	private AuthService authService;

	public void destroy()
	{
		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException
	{
		HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
		HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

		if(!checkAuthInit(httpRequest.getSession()))
		{
			initAuth(httpRequest.getSession());
		}
		chain.doFilter(httpRequest, httpResponse);

	}

	private void initAuth(HttpSession session)
	{
		if(authService == null)
		{
			authService =  (AuthService) SpringContext.getBean(System.getProperty(BaseConst.SSO_AUTH_SERVICE));;
		}
		LoginUser loginUser = (LoginUser)session.getAttribute(BaseConst.SESSION_USER_KEY);
		if(loginUser != null)
		{
			List<? extends Auth> authList  = null;
			if(loginUser.getUserId() != null  &&  loginUser.getUserId().equalsIgnoreCase("admin"))
			{
				authList = authService.queryAllAuth();

			}
			else
			{
				authList = authService.queryUserAuth(loginUser.getUserId());
			}
			String authString = makeAuthString(authList);
			String authCode = makeAuthCode(authList);
			session.setAttribute(BaseConst.SESSION_AUTH_PATH, authString);
			session.setAttribute(BaseConst.SESSION_AUTH_CODE_PATH, authCode);

		}
	}

	private boolean checkAuthInit(HttpSession session)
	{
		if(session.getAttribute(BaseConst.SESSION_AUTH_PATH) != null)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	private String makeAuthString(List<? extends Auth> authList)
	{
		StringBuffer stringBuffer = new StringBuffer(BaseConst.AUTH_SPILT);
		if(authList != null  && authList.size() > 0 )
		{
			for(Auth auth : authList)
			{
				stringBuffer.append(auth.getAuthId()).append(BaseConst.AUTH_SPILT);
			}
		}
		return stringBuffer.toString();
	}

	
	private String makeAuthCode(List<? extends Auth> authList)
	{
		StringBuffer stringBuffer = new StringBuffer(BaseConst.AUTH_SPILT);
		for(Auth auth : authList)
		{
			stringBuffer.append(auth.getAuthCode()).append(BaseConst.AUTH_SPILT);
		}
		return stringBuffer.toString();
	}
	public void init(FilterConfig arg0) throws ServletException
	{
		
	}


}
